package com.mxpio.erp.sales.controller;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.jpa.model.Order;
import com.mxpio.erp.common.sales.entity.SalesOrder;
import com.mxpio.erp.common.sales.entity.SalesOrderLine;
import com.mxpio.erp.common.sales.service.SalesOrderLineService;
import com.mxpio.erp.common.sales.service.SalesOrderService;
import com.mxpio.erp.common.service.OrderService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.CriteriaUtils;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Api(value = "SalesOrderController", tags = { "销售订单接口" })
@RestController
@RequestMapping("/erp/sales/so/")
public class SalesOrderController {

    @Autowired
    private SalesOrderService salesOrderService;
    @Autowired
    private SalesOrderLineService salesOrderLineService;
    
    @Autowired
    private OrderService orderService;

    @GetMapping("list")
    @ApiOperation(value = "销售订单列表", notes = "获取销售订单列表（无分页）", httpMethod = "GET")
    public Result<List<SalesOrder>> list(@ApiParam(name="查询参数")  String criteria) throws UnsupportedEncodingException {
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        List<SalesOrder> salesOrders = salesOrderService.list(SalesOrder.class, c);
        return Result.OK(salesOrders);
    }

    @GetMapping("page")
    @ApiOperation(value = "销售订单列表", notes = "获取销售订单列表（分页）", httpMethod = "GET")
    public Result<Page<SalesOrder>> page(@ApiParam(name="查询参数")String criteria, @ApiParam(name="每页条数")Integer pageSize, @ApiParam(name="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Criteria c = CriteriaUtils.json2Criteria(criteria);
        Page<SalesOrder> salesOrders = salesOrderService.listPage(SalesOrder.class, page, c);
        return Result.OK(salesOrders);
    }

    @GetMapping("list/{bizNo}")
    @ApiOperation(value = "根据bizNo获取销售订单", notes = "根据bizNo获取销售订单", httpMethod = "GET")
    public Result<SalesOrder> getById(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        SalesOrder salesOrder = salesOrderService.getById(SalesOrder.class, bizNo);
        return Result.OK(salesOrder);
    }

    @RequestMapping("save")
    @ApiOperation(value = "保存销售订单", notes = "保存销售订单")
    public Result<SalesOrder> save(@RequestBody SalesOrder salesOrder) {
        salesOrderService.save(salesOrder,new SmartCrudPolicyAdapter(){
        	@Override
        	public boolean beforeInsert(CrudContext context) {
        		Object o = context.getEntity();
        		if(o instanceof SalesOrderLine){
        			SalesOrder salesOrder = context.getParent();
                    ((SalesOrderLine) o).setBizNo(salesOrder.getBizNo());
        		}
        		return true;
        	}
        });
        return Result.OK(salesOrder);
    }

    @DeleteMapping("remove/{bizNos}")
    @ApiOperation(value = "根据bizNo删除销售订单", notes = "删除销售订单", httpMethod = "DELETE")
    @Transactional(readOnly = false)
    public Result<SalesOrder> remove(@ApiParam(name="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        String[] bizNo = bizNos.split(",");
        for(String key : bizNo){
        	Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, key);
        	salesOrderLineService.removeBatch(SalesOrderLine.class, c);
            salesOrderService.delete(SalesOrder.class, key);
        }
        return Result.OK();
    }

    @PutMapping("submit/{bizNo}")
    @ApiOperation(value = "提交销售订单", notes = "提交销售订单", httpMethod = "PUT")
    public Result<? extends Order> submit(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	if(so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
    		return orderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.AUDITING);
    	}else {
    		return Result.error("非开立状态不可提交");
		}
    }

    @PutMapping("audit/{bizNo}")
    @ApiOperation(value = "审核销售订单", notes = "审核销售订单", httpMethod = "PUT")
    public Result<? extends Order> audit(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	if(so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
    		return orderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.AUDITED);
    	}else {
    		return Result.error("非审核中状态不可审核");
		}
    }

    @PutMapping("abandon/{bizNo}")
    @ApiOperation(value = "弃审销售订单", notes = "弃审销售订单", httpMethod = "PUT")
    public Result<? extends Order> abandon(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	if(so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())||so.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())){
    		return orderService.updateBpmnStatus(so, OrderStatusEnums.BpmnStatus.CREATE);
    	}else{
    		return Result.error("非审核中、已审核状态不可审核");
    	}
    }

    @PutMapping("export/{bizNos}")
    @ApiOperation(value = "导出销售订单", notes = "导出销售订单", httpMethod = "PUT")
    public Result<SalesOrder> export(@ApiParam(name="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "bizNos", required = true) String bizNos) {
        //TODO:导出逻辑
        return Result.OK();
    }

    @PutMapping("open/{bizNo}")
    @ApiOperation(value = "打开销售订单", notes = "打开销售订单", httpMethod = "PUT")
    public Result<? extends Order> open(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	return orderService.updateCloseStatus(so, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{bizNo}")
    @ApiOperation(value = "关闭销售订单", notes = "关闭销售订单", httpMethod = "PUT")
    public Result<? extends Order> close(@ApiParam(name="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
    	SalesOrder so = salesOrderService.getById(SalesOrder.class,bizNo);
    	return orderService.updateCloseStatus(so, OrderStatusEnums.CloseStatus.CLOSED);
    }

}
